<template>
  <div class="buildLogModal">
    <a-modal
      v-model:open="visible"
      :title="'构建日志'"
      :footer="null"
      :width="1000"
      :body-style="{ padding: '16px' }"
      mask-closable
      @cancel="closeModal"
    >
      <div class="log-content">
        <span v-if="!logContent" class="no-data">暂无内容</span>
        <p v-html="logContent"></p>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { nextTick, ref } from 'vue'

  import { mirrorManageApi } from '@/services/api'

  const visible = ref(false)
  const logId = ref()
  const logContent = ref()
  const startLine = ref(0)
  let getLogTimer = null

  const getBuildLog = async () => {
    try {
      let res = await mirrorManageApi.getBuildLog({ startLine: startLine.value }, { urlParams: { id: logId.value } })
      logContent.value = (logContent.value + res.data.content).replace(/\n/g, '<br>')
      startLine.value = res.data.currentRow
      if (!res.data.roundFlag) {
        clearInterval(getLogTimer)
      }

      nextTick(() => {
        let scrollHeight = document.querySelector('.log-content').scrollHeight
        document.querySelector('.log-content')?.scrollTo(0, scrollHeight)
      })
    } catch {
      clearInterval(getLogTimer)
    }
  }
  const timerGetData = () => {
    if (getLogTimer) {
      clearInterval(getLogTimer)
    }
    getLogTimer = setInterval(async () => {
      await getBuildLog()
    }, 3000)
  }

  const open = (id: number | string) => {
    logContent.value = ''
    logId.value = id
    visible.value = true
    startLine.value = 0
    getBuildLog()
    timerGetData()
  }

  const closeModal = () => {
    clearInterval(getLogTimer)
  }

  defineExpose({ open })
</script>

<style lang="less" scoped>
  .log-content {
    overflow-y: auto;
    padding: 21px 8px;
    height: 680px;
    background: #f2f2f5;
    border: 1px solid #c4c4c7;
    border-radius: 4px;

    &::-webkit-scrollbar {
      width: 6px; /* Width of the vertical scrollbar */
    }

    &::-webkit-scrollbar-track {
      border-radius: 100px; /* Scrollbar track rounded corners */
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(25, 25, 48, 0.2);
      border-radius: 10px; /* Scrollbar thumb rounded corners */
    }

    &::-webkit-scrollbar-thumb:hover {
      background: rgba(25, 25, 48, 0.3);
    }

    .no-data {
      display: block;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 auto;
      height: 100%;
      text-align: center;
      color: @text04;
    }
  }
</style>
